<template>
  <Dialog
    v-model="dialogVisible"
    width="800px"
    :title="typeIndex === 'add' ? t('staff.add') : t('staff.edit')"
    :before-close="() => closeDialog(formRef)"
    :close-on-click-modal="true"
    maxHeight="680px"
  >
    <!-- 主表单部分 -->
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="110px">
      <el-form-item :label="t('minerPool.name')" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item :label="t('minerPool.image')" prop="image">
        <UploadFile
          class="w-100%"
          url="/common/uploadFile"
          drag
          :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'docx', 'doc', 'xlsx', 'xls']"
          :params="{ directory: 5 }"
          :limit="1"
          :fileListMap="picList"
          upload-file-button-name="点击上传或拖拽到此处上传"
          buttonWidth="100%"
          :button-link="true"
          :show-file-list="true"
          @upload-success-res="handleUploadCallback"
          @handle-remove-file="handleRemoveFile"
          @handle-picture-card-preview="handlePictureCardPreview"
        />
      </el-form-item>

      <el-form-item :label="t('minerPool.link')" prop="link">
        <el-input v-model="form.link" />
      </el-form-item>

      <!-- 币种选择按钮 -->
      <el-form-item :label="t('minerPool.support_currency')" prop="support_currency">
        <el-button type="primary" @click="openCurrencyDialog">
          {{ t('minerPool.select_currency') }} ({{ selectedCurrencies.length }})
        </el-button>
        <div class="mt-2" v-if="selectedCurrencies.length > 0">
          <el-tag v-for="currency in selectedCurrencies" :key="currency.id" class="mr-2 mb-2">
            {{ currency.label }}
          </el-tag>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)">{{ t('common.cancel') }} </el-button>
      <el-button type="primary" @click="submit(formRef)">{{ t('common.save') }} </el-button>
    </template>

    <!-- 币种选择弹框 -->
    <Dialog
      v-model="currencyDialogVisible"
      :title="t('minerPool.select_currency')"
      :maxHeight="'800px'"
      class="currency-dialog"
      @close="resetCurrencyDialog"
      width="1800px"
    >
      <div>
        <!-- 搜索框放在左侧 -->
        <div class="search-container mb-4">
          <el-input
            v-model="searchKeyword"
            :placeholder="t('minerPool.search_currency_placeholder')"
            clearable
            class="search-input"
            @input="handleSearchInput"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 币种表格 -->
        <el-table
          ref="currencyTableRef"
          :data="filteredCurrencyList"
          style="width: 100%; height: 800px"
          @selection-change="handleSelectionChange"
          :reserve-selection="false"
          v-loading="currencyLoading"
          row-key="id"
        >
          <!-- 币种选择复选框列 -->
          <el-table-column type="selection" width="55" fixed="left" reserve-selection />

          <el-table-column
            prop="name"
            :label="t('minerPool.currency_name')"
            fixed="left"
            width="100"
          />

          <!-- 动态生成费率类型列 -->
          <template v-for="rate in rateTypes" :key="rate.value">
            <!-- 启用状态列 - 宽度调整为80px -->
            <el-table-column :label="`${rate.label} (启用)`" width="90">
              <template #default="{ row }">
                <el-checkbox
                  v-model="row.rateEnabled[rate.value]"
                  @change="handleRateToggle(row, rate)"
                />
              </template>
            </el-table-column>

            <!-- 费率输入列 - 宽度调整为120px -->
            <el-table-column :label="`${rate.label} (费率)`" width="150" v-if="rate.hasRate">
              <template #default="{ row }">
                <div v-if="row.rateEnabled[rate.value]" class="rate-input-container">
                  <el-input-number
                    v-model="row.rates[rate.value]"
                    :precision="2"
                    :step="0.01"
                    :min="0"
                    :max="100"
                    controls-position="right"
                    size="small"
                    @blur="validateRate(row, rate.value)"
                  >
                    <template #append>%</template>
                  </el-input-number>
                </div>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <template #footer>
        <el-button
          @click="
            () => {
              resetCurrencyDialog()
              currencyDialogVisible = false
            }
          "
        >
          {{ t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="saveSelectedCurrencies">{{ t('common.save') }}</el-button>
      </template>
    </Dialog>
  </Dialog>
</template>

<script setup lang="ts">
import { createImageViewer } from '@/components/ImageViewer'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import { editInfoApi, createDataApi } from '@/api/minerPool'
import { getCurrencyListApi } from '@/api/currency'
import { nextTick, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'

const emit = defineEmits(['refresh'])
const { t } = useI18n()

// 费率类型配置
const rateTypes = ref([
  { value: 'RESELL', label: 'RESELL', hasRate: false },
  { value: 'PPS', label: 'PPS', hasRate: true },
  { value: 'PPS+', label: 'PPS+', hasRate: true },
  { value: 'PPLNS', label: 'PPLNS', hasRate: true },
  { value: 'FPPS', label: 'FPPS', hasRate: true }, // 修复: 将 hasate 改为 hasRate
  { value: 'PROP', label: 'PROP', hasRate: true },
  { value: 'TIDES', label: 'TIDES', hasRate: true }
])

// 状态变量
const dialogVisible = ref<boolean>(false)
const currencyDialogVisible = ref<boolean>(false)
const typeIndex = ref<string>()
const currencyList = ref<Array<Record<string, any>>>([]) // 原始币种数据
const selectedCurrencies = ref<Array<Record<string, any>>>([])
const currencyTableRef = ref<any>(null)
const selectedCurrencyRows = ref<Array<any>>([])

// 搜索相关变量
const searchKeyword = ref('')
const filteredCurrencyList = ref<Array<Record<string, any>>>([]) // 过滤后的币种列表
const debounceTimer = ref<ReturnType<typeof setTimeout> | null>(null)
const currencyLoading = ref(false)

// ：优化币种列表初始化方法
const initCurrencyList = async () => {
  console.log('🔄 [DEBUG] 开始初始化币种列表')
  currencyLoading.value = true

  try {
    const resp = await getCurrencyListApi({})
    console.log('🔍 [DEBUG] 币种API响应:', JSON.stringify(resp, null, 2))

    if (resp?.code === 0 && resp?.data?.list) {
      // 重建币种数据结构
      currencyList.value = resp.data.list.map((item) => {
        const newItem = {
          id: item.id || item.value || '',
          name: item.name || '',
          label: item.label || '',
          value: item.value || '',
          rateEnabled: Object.fromEntries(rateTypes.value.map((rate) => [rate.value, false])),
          rates: Object.fromEntries(
            rateTypes.value.filter((r) => r.hasRate).map((rate) => [rate.value, 0])
          )
        }
        return newItem
      })

      console.log('✅ [DEBUG] 币种列表初始化成功，数量:', currencyList.value.length)

      // ：初始化过滤列表（创建新数组）
      filteredCurrencyList.value = currencyList.value.map((item) => ({ ...item }))
    } else {
      console.error('❌ [ERROR] 币种列表初始化失败，API响应:', JSON.stringify(resp))
      currencyList.value = []
      filteredCurrencyList.value = []
      ElMessage.error('币种数据加载失败')
    }
  } catch (e) {
    console.error('❌ [ERROR] 币种列表初始化异常:', e)
    currencyList.value = []
    filteredCurrencyList.value = []
    ElMessage.error('币种数据加载发生错误')
  } finally {
    currencyLoading.value = false
    console.log('🔄 [DEBUG] 币种列表初始化完成')
  }
}

// ：优化弹窗重置方法
const resetCurrencyDialog = () => {
  console.log('🔄 [DEBUG] 重置币种弹窗数据')

  // 清空选中行
  selectedCurrencyRows.value = []

  // 重置搜索条件
  searchKeyword.value = ''

  // ：重置过滤列表（创建新数组）
  filteredCurrencyList.value = currencyList.value.map((item) => ({ ...item }))

  // 清除防抖定时器
  if (debounceTimer.value) {
    clearTimeout(debounceTimer.value)
    debounceTimer.value = null
  }

  console.log('✅ [DEBUG] 币种弹窗重置完成')
}

// 处理搜索输入（带防抖）
const handleSearchInput = () => {
  if (debounceTimer.value) {
    clearTimeout(debounceTimer.value)
    debounceTimer.value = null
  }

  debounceTimer.value = setTimeout(() => {
    performCurrencySearch()
  }, 1000)
}

// 执行币种模糊搜索
const performCurrencySearch = () => {
  const keyword = searchKeyword.value.trim().toLowerCase()

  if (!keyword) {
    // 搜索词为空时显示全部币种
    filteredCurrencyList.value = currencyList.value.map((item) => ({ ...item }))
    console.log('✅ [DEBUG] 清空搜索，显示全部币种')
    return
  }

  // 过滤匹配的币种
  filteredCurrencyList.value = currencyList.value
    .filter((currency) => {
      const name = String(currency.name || '').toLowerCase()
      const label = String(currency.label || '').toLowerCase()
      return name.includes(keyword) || label.includes(keyword)
    })
    .map((item) => ({ ...item }))

  console.log(
    `✅ [DEBUG] 币种模糊搜索完成，关键字: ${keyword}，结果数量: ${filteredCurrencyList.value.length}`
  )
}

// ：优化应用rating配置方法
const applyRatingConfig = () => {
  if (!form.value.rating) return

  try {
    const ratingData =
      typeof form.value.rating === 'string' ? JSON.parse(form.value.rating) : form.value.rating

    console.log('🔄 [DEBUG] 应用rating配置:', JSON.stringify(ratingData, null, 2))

    Object.keys(ratingData).forEach((currencyId) => {
      const currencyInfo = ratingData[currencyId]
      const currency = currencyList.value.find((c) => String(c.id) === String(currencyId))

      if (currency && currencyInfo.selectedRates) {
        // 重置所有费率状态
        rateTypes.value.forEach((rate) => {
          currency.rateEnabled[rate.value] = false
        })

        // 应用选中状态
        currencyInfo.selectedRates.forEach((rateType) => {
          if (currency.rateEnabled[rateType] !== undefined) {
            currency.rateEnabled[rateType] = true
          }

          // 应用费率值
          if (currencyInfo.rates?.[rateType] !== undefined) {
            const rateValue = currencyInfo.rates[rateType]
            const numValue = parseFloat(rateValue)
            currency.rates[rateType] = isNaN(numValue) ? 0 : numValue
          }
        })
      }
    })

    console.log('✅ [DEBUG] rating配置应用成功')
  } catch (e) {
    console.error('❌ [ERROR] 应用rating配置失败', e)
  }
}

// ：优化获取回显数据方法
const getBackShow = async (type: string, row?: Record<string, any>) => {
  console.log('🚀 [DEBUG] 进入getBackShow方法，类型:', type)
  typeIndex.value = type
  picList.value = []

  // 重置变量
  fileObj.value = null
  selectedCurrencies.value = []

  try {
    // 确保币种数据加载完成
    await initCurrencyList()

    if (type === 'edit' && row) {
      console.log('📝 [DEBUG] 编辑模式，原始数据:', JSON.stringify(row, null, 2))
      form.value = { ...row }

      // 确保rating字段存在
      form.value.rating = row.rating || {}
      console.log('🔍 [DEBUG] 原始rating数据:', JSON.stringify(form.value.rating, null, 2))

      // 确保币种ID正确处理
      const supportCurrencyIds =
        typeof row.support_currency === 'string'
          ? row.support_currency.split(',')
          : Array.isArray(row.support_currency)
            ? row.support_currency
            : []

      form.value.support_currency = supportCurrencyIds

      // 正确回显已选择币种的标签
      const currencyMap = new Map(currencyList.value.map((c) => [String(c.id), c]))
      selectedCurrencies.value = supportCurrencyIds
        .map((id) => {
          const currency = currencyMap.get(String(id))
          return currency ? { id: currency.id, label: currency.label } : null
        })
        .filter(Boolean) as Record<string, any>[]

      console.log(
        '✅ [DEBUG] 已选择的币种标签:',
        selectedCurrencies.value.map((c) => c.label)
      )

      // 应用rating配置
      applyRatingConfig()

      // 正确回显图片
      if (row.image && (row.imageId || row.image)) {
        picList.value = [
          {
            name: row.imageName || row.image.split('/').pop() || '图片',
            id: row.imageId || 0,
            url: row.image
          }
        ]
        fileObj.value = { ...picList.value[0] }
        console.log('🖼️ [DEBUG] 图片回显数据:', picList.value[0])
      }
    } else {
      // 新增模式
      form.value = {
        name: '',
        image: 0,
        link: '',
        support_currency: [],
        rating: {}
      }
    }

    // 强制UI更新
    await nextTick()
  } catch (e) {
    console.error('❌ [ERROR] getBackShow方法执行失败', e)
  }
}

defineExpose({
  dialogVisible,
  getBackShow
})

// ：优化打开币种选择弹窗方法
const openCurrencyDialog = () => {
  console.log('🔍 [DEBUG] 打开币种选择弹窗')
  resetCurrencyDialog() // 先重置数据
  currencyDialogVisible.value = true

  // 应用rating配置
  applyRatingConfig()

  // 在nextTick中执行回显逻辑
  nextTick(() => {
    let supportCurrencyIds = form.value.support_currency

    // 确保支持多种数据类型：字符串或数组
    if (typeof supportCurrencyIds === 'string') {
      supportCurrencyIds = supportCurrencyIds.split(',')
    } else if (!Array.isArray(supportCurrencyIds)) {
      supportCurrencyIds = []
    }

    console.log('🔍 [DEBUG] 处理后的币种ID数组:', supportCurrencyIds)

    if (currencyTableRef.value && supportCurrencyIds.length > 0) {
      console.log('🔍 [DEBUG] 开始回显选中的币种行')

      // ：确保表格正确初始化
      currencyTableRef.value.clearSelection()

      // 创建ID映射表确保类型一致
      const idMap = new Map(currencyList.value.map((c) => [String(c.id), c]))

      // 设置选中状态
      supportCurrencyIds.forEach((id) => {
        const currency = idMap.get(String(id))
        if (currency) {
          console.log(`✅ [DEBUG] 选中币种ID: ${id} (${currency.label})`)

          // ：在过滤列表中查找匹配的行
          const tableRow = filteredCurrencyList.value.find((c) => String(c.id) === String(id))
          if (tableRow) {
            currencyTableRef.value.toggleRowSelection(tableRow, true)
          }
        }
      })
    }
  })
}

// 处理币种选择变化
const handleSelectionChange = (rows: any[]) => {
  console.log(
    '🔍 [DEBUG] 处理币种选择变化，当前选中行:',
    rows.map((r) => r.label)
  )
  selectedCurrencyRows.value = rows
}

// 保存选择的币种
const saveSelectedCurrencies = () => {
  console.log('💾 [DEBUG] 保存选择的币种')

  // 获取选中的币种ID
  const selectedIds = selectedCurrencyRows.value.map((row) => row.id).join(',')

  // 更新表单的币种ID
  form.value.support_currency = selectedIds
  console.log(`🔍 [DEBUG] 更新表单币种ID: ${selectedIds}`)

  // 更新显示的币种标签
  selectedCurrencies.value = selectedCurrencyRows.value.map((row) => ({
    id: row.id,
    label: row.label
  }))

  console.log(
    '🔍 [DEBUG] 更新选中的币种标签:',
    selectedCurrencies.value.map((c) => c.label)
  )

  // 保存每个币种的费率配置到form.rating
  const ratingData = {}
  selectedCurrencyRows.value.forEach((row) => {
    // 获取该币种所有选中的费率类型
    const selectedRates = Object.keys(row.rateEnabled).filter((key) => row.rateEnabled[key])

    const rates = {}
    // 收集有效费率设置
    selectedRates.forEach((rateType) => {
      const rateValue = row.rates[rateType]
      if (rateValue !== undefined && rateValue !== '') {
        rates[rateType] = parseFloat(rateValue)
      }
    })

    ratingData[row.id] = {
      selectedRates, // 选中的费率类型
      rates // 费率值
    }
    console.log(
      `✅ [DEBUG] 保存币种 ${row.label} 的费率配置:`,
      JSON.stringify({ selectedRates, rates }, null, 2)
    )
  })

  // 更新表单的rating字段
  form.value.rating = ratingData
  console.log('✅ [DEBUG] 更新表单rating字段:', JSON.stringify(ratingData, null, 2))

  currencyDialogVisible.value = false
}

// 费率验证方法
const validateRate = (row: any, rateType: string) => {
  const value = row.rates[rateType]
  if (value === undefined || value === '') return

  const numValue = parseFloat(value)
  if (isNaN(numValue)) {
    ElMessage.error(t('minerPool.rateNumberRequired'))
    return
  }

  if (numValue < 0) {
    row.rates[rateType] = 0
    ElMessage.error(t('minerPool.rateMinError'))
  } else if (numValue > 100) {
    row.rates[rateType] = 100
    ElMessage.error(t('minerPool.rateMaxError'))
  } else {
    // toFixed(2) 返回字符串，需转回 Number
    row.rates[rateType] = parseFloat(numValue.toFixed(2))
  }

  autoSelectCurrency(row)
}

// 处理费率类型切换
const handleRateToggle = (row: any, rateType: any) => {
  console.log(
    '🔍 [DEBUG] 费率类型切换，币种:',
    row.label,
    '费率类型:',
    rateType.value,
    '新状态:',
    row.rateEnabled[rateType.value]
  )

  if (
    row.rateEnabled[rateType.value] &&
    rateType.hasRate &&
    (row.rates[rateType.value] === null || row.rates[rateType.value] === undefined)
  ) {
    console.log('🔄 [DEBUG] 费率类型启用但值为空，初始化为0')
    row.rates[rateType.value] = 0
  }

  // 设置费率后自动选中币种
  if (row.rateEnabled[rateType.value]) {
    console.log('✅ [DEBUG] 检测到费率启用，自动选中币种:', row.label)
    autoSelectCurrency(row)
  }
}

// 自动选中币种
const autoSelectCurrency = (row: any) => {
  console.log('🔍 [DEBUG] 尝试自动选中币种:', row.label)

  // 检查是否已选中
  const isSelected = selectedCurrencyRows.value.some((selectedRow) => selectedRow.id === row.id)

  if (!isSelected) {
    // 添加到选中列表
    selectedCurrencyRows.value = [...selectedCurrencyRows.value, row]
    console.log('✅ [DEBUG] 币种添加到选中列表:', row.label)

    // 更新表格选择状态
    if (currencyTableRef.value) {
      currencyTableRef.value.toggleRowSelection(row, true)
      console.log('✅ [DEBUG] 表格选中状态更新成功')
    }
  }
}

// 表单引用和规则
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  name: '',
  image: 0,
  link: '',
  support_currency: [],
  rating: {}
})

const rules = ref<FormRules>({
  name: [
    {
      required: true,
      message: t('minerPool.nameRequired'),
      trigger: ['blur']
    }
  ],
  image: [
    {
      required: true,
      message: t('minerPool.imageRequired'),
      trigger: ['blur']
    }
  ],
  link: [
    {
      required: true,
      message: t('minerPool.linkRequired'),
      trigger: ['blur']
    }
  ],
  support_currency: [
    {
      required: true,
      message: t('minerPool.currencyRequired'),
      trigger: ['blur'],
      validator: (_, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error(t('minerPool.currencyRequired')))
        } else {
          callback()
        }
      }
    }
  ]
})

const picList = ref<any[]>([])
const fileObj = ref<any>(null)

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        form.value.image = fileObj.value ? fileObj.value.id : 0

        form.value.support_currency = selectedCurrencies.value
          .map((currency) => currency.id)
          .join(',')

        console.log('✅ [DEBUG] 提交表单数据:', JSON.stringify(form.value, null, 2))

        const resp =
          typeIndex.value === 'add'
            ? await createDataApi(form.value)
            : await editInfoApi(form.value)

        if (resp && resp.code === 0) {
          console.log('✅ [DEBUG] 矿池信息提交成功')
          ElMessage.success(
            typeIndex.value === 'add' ? t('minerPool.createSuccess') : t('minerPool.updateSuccess')
          )
          closeDialog(formEl)
          emit('refresh')
        } else {
          console.error('❌ [ERROR] 矿池信息提交失败，响应码:', resp?.code)
          ElMessage.error((resp as any)?.msg || '提交矿池信息失败')
        }
      } catch (error) {
        console.error('❌ [ERROR] 矿池信息提交失败', error)
        ElMessage.error('提交矿池信息失败，请检查数据格式')
      }
    } else {
      console.warn('⚠️ [WARNING] 表单验证未通过')
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    name: '',
    image: 0,
    link: '',
    support_currency: [],
    rating: {}
  }
  selectedCurrencies.value = []
  fileObj.value = null
  picList.value = []
  formEl.resetFields()
  dialogVisible.value = false
  console.log('🚪 [DEBUG] 关闭主弹窗，重置所有数据')
}

//上传成功回调
const handleUploadCallback = (val: any) => {
  console.log('✅ [DEBUG] 文件上传成功:', val)
  fileObj.value = val
  form.value.image = fileObj.value.id
}

const handleRemoveFile = (val: any) => {
  console.log('🗑️ [DEBUG] 移除文件:', val)
  fileObj.value = null
  picList.value = []
}

const handlePictureCardPreview = (url: any) => {
  try {
    if (!url) return
    if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(url)) {
      console.log('🖼️ [DEBUG] 预览图片:', url)
      return createImageViewer({
        urlList: [url]
      })
    }
    console.log('🔗 [DEBUG] 打开链接:', url)
    window.open(url)
  } catch (error) {
    console.error('❌ [ERROR] 预览图片失败:', error)
  }
}
</script>

<style lang="less" scoped>
@media (width <= 768px) {
  .currency-dialog .el-dialog {
    width: 98% !important; /* 小屏幕弹窗全幅显示 */
  }

  .el-table-column {
    min-width: 60px !important; /* 防内容截断 */
  }
}

/* 移动端适配 */
@media (width <= 768px) {
  .search-container .el-input {
    width: 100%;
  }
}

.m-r-4 {
  margin-right: 16px;
}

.mt-2 {
  margin-top: 0.5rem;
}

.mb-2 {
  margin-bottom: 0.5rem;
}

.mr-2 {
  margin-right: 0.5rem;
}

/* 币种表格容器 */
.currency-table-container {
  width: 100%;
  height: 500px; /* 添加固定高度 */
  overflow: auto; /* 添加滚动条 */

  /* 修复表格宽度问题 */
  .el-table {
    width: 100%;
    table-layout: fixed;

    .el-table__header-wrapper,
    .el-table__body-wrapper {
      width: 100% !important;
      table-layout: fixed;
    }
  }
}

/* 弹框穿透样式 */
:deep(.currency-dialog) {
  .el-dialog {
    width: 1600px !important;
    max-width: 95vw;
    border-radius: 8px;

    &__body {
      max-height: 70vh;
      padding: 15px 20px;
      overflow: auto;
    }
  }

  .el-input-number {
    width: 100px;

    .el-input__inner {
      padding: 0 5px;
      text-align: right;
    }
  }

  .el-table {
    th,
    td {
      padding: 6px 0;
    }

    .el-table__cell {
      padding: 0 2px;
      box-sizing: border-box;

      .cell {
        padding: 0 2px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

.rate-input-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

/* 搜索框样式 */
.search-container {
  margin-bottom: 15px;
  text-align: left;

  .el-input {
    width: 300px;
  }
}
</style>
